package cate.game.pvp.eliterace.handler;

import cate.game.pvp.eliterace.data.EliteRaceRedPacketRecord;
import cate.game.pvp.eliterace.data.EliteRaceRedPacketRecordData;
import cate.game.pvp.eliterace.data.EliteRaceSpec;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;

public class BothEliteRaceRedPacketOperation implements EliteRaceRedPacketOperation {

    private final EliteRaceRedPacketRecordData rpRdData;

    public BothEliteRaceRedPacketOperation(Supplier<EliteRaceRedPacketRecordData> redPacketRecordDataSupplier) {
        this.rpRdData = Objects.requireNonNull(redPacketRecordDataSupplier.get());
    }

    @Override
    public EliteRaceRedPacketRecord query(EliteRaceSpec spec, String uid) {
        if (Objects.isNull(spec) || !StringUtils.hasLength(uid)) {
            return null;
        }

        Map<String, EliteRaceRedPacketRecord> indexMap = rpRdData.getIndex(spec.toString());
        if (CollectionUtils.isEmpty(indexMap)) {
            return null;
        }

        return indexMap.values()
                .stream()
                .filter(rd -> StringUtils.endsWithIgnoreCase(uid, rd.getUid()))
                .findFirst()
                .orElse(null);
    }

    @Override
    public List<EliteRaceRedPacketRecord> query(EliteRaceSpec spec, long limit) {
        if (Objects.isNull(spec)) {
            return null;
        }
        Map<String, EliteRaceRedPacketRecord> indexMap = rpRdData.getIndex(spec.toString());
        if (CollectionUtils.isEmpty(indexMap)) {
            return null;
        }

        return indexMap.values()
                .stream()
                .limit(limit)
                .collect(Collectors.toList());
    }

    @Override
    public void insert(EliteRaceSpec spec, EliteRaceRedPacketRecord record) {
        rpRdData.addValue(record);
        rpRdData.getIndex(spec.toString()).put(record.getIndexedKey(), record);
    }
}
